/*
高德地图相关
*/

angular.module('driver').controller('MapCtrl', ['$scope', '$rootScope', '$ionicLoading', '$ionicPopup', '$http', '$meteor', '$ionicPlatform', 'Marker', 'Map', 'GPS', 'Transfer', '$localstorage', 'Path',
  function($scope, $rootScope, $ionicLoading, $ionicPopup, $http,
    $meteor, $ionicPlatform, Marker, Map, GPS, Transfer, $localstorage, Path) {


    $meteor.autorun($scope, function() {
      $meteor.subscribe('users', Session.get('location')).then(function(subscriptionHandle) {
        $scope.users = $meteor.collection(Meteor.users);
      });
    });

    $scope.$watch('users', function(newValue, oldValue) {
      if (newValue)
        Marker.doDriverMarker(newValue, oldValue, $scope.map);
    }, true);

    $meteor.subscribe('userrequests').then(function(subscriptionHandle) {
      $scope.userrequests = $meteor.collection(UserRequests);
    });
    $scope.$watch('userrequests', function(newValue, oldValue) {
      //console.log(newValue, oldValue);
      //console.log(Roles.userIsInRole(Meteor.userId(), 'driver'));
      if (newValue && Roles.userIsInRole(Meteor.userId(), 'driver'))
        Marker.doReqMarker(newValue, oldValue, $scope.map);
    }, true);

    $meteor.subscribe('userStatus').then(function(subscriptionHandle) {
      $scope.userStatus = $meteor.object(Meteor.users, {
        '_id': Meteor.userId()
      });
      $scope.$watch('userStatus', function(newValue, oldValue) {});

    });

    $meteor.subscribe('myOrders').then(function(subscriptionHandle) {
      $scope.myOrders = $meteor.collection(Orders);
      $scope.$watch('myOrders', function(newValue, oldValue) {
        if (oldValue.length > 0 && newValue.length == 0) {
          if (Roles.userIsInRole(Meteor.userId(), 'driver')) {} else {
            var reqId = oldValue[0].reqId;
            var order = oldValue[0];
            //console.log(order);
            $meteor.call('getRequestInfo', reqId).then(
              function(request) {
                /*
                console.log(order);
                var lineArr = new Array(); //创建线覆盖物节点坐标数组
                order.path.forEach(function(p) {
                  lineArr.push(new AMap.LngLat(p.lng, p.lat));
                });
                polyline = new AMap.Polyline({
                  path: lineArr, //设置线覆盖物路径
                  strokeColor: "#3366FF", //线颜色
                  strokeOpacity: 0.7, //线透明度 
                  strokeWeight: 4, //线宽
                  strokeStyle: "dashed", //线样式
                  strokeDasharray: [10, 5] //补充线样式 
                });
                polyline.setMap($scope.map);
                */
                var length = order.pathLength;
                var price = calcPrice({
                  arrive_time: order.acceptTime,
                  start_time: order.startTime,
                  driver_length: length
                });
                var confirmPopup = $ionicPopup.confirm({
                  title: '到达',
                  template: '共行驶' + length + '米, 需要支付' + price + '元',
                  cancelText: '现金支付',
                  cancelType: 'button-royal button-outline',
                  //okText: '无线支付',
                  //okType: 'button-assertive button-outline',
                });
                confirmPopup.then(function(res) {

                });
              },
              function(err) {

              }
            );

          }
        }
      }, true);
    });



    $scope.sort = {
      _id: 1
    };

    $scope.location = Map.getLocation();

    //var isCheckAccuracy = false;
    var checkAccuracy = function(accuracy) {
      //if (isCheckAccuracy) return;
      if (!Meteor.isCordova) return;

      if (accuracy !== null) return;

      $checkGPS.check().then(function() {
        //isCheckAccuracy = true;
      }, function() {
        $scope.showAlert('定位结果可能不准确', '请打开设备上的GPS');
      });
    };

    $scope.addMarkers = function(users, map) {
      Marker.addMarkers(users, $scope.map, $scope.showAlert);
    };
    // An alert dialog
    $scope.showAlert = function(title, temp) {
      //console.log($ionicPopup);
      var alertPopup = $ionicPopup.alert({
        title: title,
        template: temp,
        okType: 'button-royal button-outline',
        okText: '确定'
      });
      alertPopup.then(function(res) {
        //console.log('Thank you for not eating my delicious ice cream cone');
      });
    };


    var selfMarker = null;
    var setSelfMarker = function(position) {
      if (selfMarker)
        selfMarker.setMap(null);

      selfMarker = new AMap.Marker({
        icon: "/marker_sprite.png",
        position: [position.lng, position.lat]
      });

      selfMarker.setMap($scope.map);
    };

    var onSuccess = function(pos) {
      console.log(pos);

      if (pos.longtitude && pos.latitude) { //百度定位
        pos.position = {
          lng: pos.longtitude,
          lat: pos.latitude
        };
        pos.accuracy = pos.radius;
      }
      $scope.$apply(function() {
        $scope.gettingPos = false;
      });

      var lnglat = new AMap.LngLat(pos.position.lng, pos.position.lat);
      setSelfMarker(pos.position);
      $scope.map.panBy(5,10);   //地图按像素平移
      $scope.map.panTo(lnglat);  //地图中心点平移到指定位置
      if (Meteor.isCordova)
        $meteor.call('updateAddress', pos.address);
      else {
        Map.MGeocoder.getAddress(lnglat, function(status, result) {
          if (status === 'complete' && result.info === 'OK') {
            //geocoder_CallBack(result);
            $meteor.call('updateAddress', result.regeocode.formattedAddress);
          }
        });
      }
      Session.set('location', [pos.position.lng, pos.position.lat]);
      Map.setLocation(pos.position);
      $meteor.call('updateLocation', pos.position);
      Path.addPosition(pos);
      //checkAccuracy(pos.accuracy);
    };
    var onError = function() {
      console.log(err);
      //$ionicLoading.hide();
      $scope.$apply(function() {
        $scope.gettingPos = false;
      });
    };

    $scope.mapCreated = function(map) {
      //    console.log('--', map);
      $scope.map = map;

      var MGeocoder;
      //加载地理编码插件
      AMap.service(["AMap.Geocoder"], function() {
        MGeocoder = new AMap.Geocoder({
          radius: 1000,
          extensions: "all"
        });
        Map.MGeocoder = MGeocoder;
      });


      $scope.map.plugin('AMap.Geolocation', function() {
        geolocation = new AMap.Geolocation({
          enableHighAccuracy: true, //是否使用高精度定位，默认:true
          timeout: 20000, //超过20秒后停止定位，默认：无穷大
          maximumAge: 10000, //定位结果缓存10000毫秒，默认：0
          convert: true, //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
          showButton: true, //显示定位按钮，默认：true
          buttonPosition: 'LB', //定位按钮停靠位置，默认：'LB'，左下角
          buttonOffset: new AMap.Pixel(15, 55), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
          showMarker: true, //定位成功后在定位到的位置显示点标记，默认：true
          showCircle: true, //定位成功后用圆圈表示定位精度范围，默认：true
          panToLocation: true, //定位成功后将定位到的位置作为地图中心点，默认：true
          zoomToAccuracy: true //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
        });
        Map.instance = $scope.map;
        Map.geolocation = geolocation;
        //console.log(Map, Map.instance);
        geo = geolocation;
        //$scope.map.addControl(geolocation);

        AMap.event.addListener(geolocation, 'complete', onSuccess); //返回定位信息
        AMap.event.addListener(geolocation, 'error', onError); //返回定位出错信息
        if (Meteor.isCordova)
          window.LocationPlugin.getLocation(onSuccess, onError);
        else
          Map.geolocation.getCurrentPosition();
        $scope.gettingPos = true;
      });
    };

    // check login code
    $ionicPlatform.ready(function() {
      //Map.geolocation.getCurrentPosition();
    });

    $scope.onHold = function() {

      var confirmPopup = $ionicPopup.confirm({
        title: '温馨提示',
        template: '正在为您联络代驾司机，确定现在要取消订单？',
        cancelText: '继续等待',
        cancelType: 'button-royal button-outline',
        okText: '取消订单',
        okType: 'button-assertive button-outline',
      });
      confirmPopup.then(function(res) {
        if (res) {
          $meteor.call('cancelRequest', Meteor.userId()).then(
            function(data) {
              $meteor.call('setRequest', Meteor.userId(), false);
              $scope.searching = false;
            },
            function(err) {}
          );
          //console.log('取消订单');
        } else {
          //console.log('继续等待');
        }
      });


    };

    $meteor.subscribe('currentOrder').then(function(subscriptionHandle) {
      $scope.orders = $meteor.collection(Orders);
    });

    $scope.service = function(order) {
      //$state.go('currentOrder');

      if (!Roles.userIsInRole(Meteor.userId(), 'driver'))
        return;
      if (order.state === 'accept') {
        $meteor.call('startService', order._id);
        $meteor.call('changeState', 'working');
        /*
                var timeRecord = 0;
                var onSuccess = function (position) {
                  now = Date.now();
                  if (now - timeRecord < 15000)
                    return;
                  timeRecord = Date.now();

                  var marGeo = Transfer.transfer(position.coords.latitude, position.coords.longitude);
                  var lat  = marGeo.lat;
                  var lng = marGeo.lng;
                  Path.addPosition(marGeo);
                  //$meteor.call('pushPosition', lat, lng);
                };
                var onError = function (err) {
                  alert(err.messages);
                };
        */
        Path.initialPath();
        //GPS.watchPosition(onSuccess, onError);

        Map.watchPosition();
      } else if (order.state === 'started') {
        Path.stop();
        //GPS.stopWatch();
        Map.stopWatch();

        var lineArr = new Array(); //创建线覆盖物节点坐标数组
        Path.array.forEach(function(p) {
          lineArr.push(new AMap.LngLat(p.lng, p.lat));
        });
        polyline = new AMap.Polyline({
          path: lineArr, //设置线覆盖物路径
          strokeColor: "#3366FF", //线颜色
          strokeOpacity: 0.8, //线透明度 
          strokeWeight: 5, //线宽
          strokeStyle: "dashed", //线样式
          strokeDasharray: [10, 5] //补充线样式 
        });
        polyline.setMap($scope.map);
        var length = polyline.getLength();

        $meteor.call('setPathLength', order._id, (length || 0));
        $meteor.call('completeService', order._id);
        $meteor.call('changeState', 'idled'); //完成工作后改变个人状态为‘空闲’
        $meteor.call('setRequest', order.userId, false);

        var price = calcPrice({
          arrive_time: order.acceptTime,
          start_time: order.startTime,
          driver_length: length
        });

        var confirmPopup = $ionicPopup.confirm({
          title: '结束',
          template: '共行驶' + length + '米, 需要支付' + price + '元, 等待用户支付...',
          cancelText: '未结束',
          cancelType: 'button-royal button-outline',
          okText: '已到达',
          okType: 'button-assertive button-outline',
        });
        confirmPopup.then(function(res) {

        });


      }
    };
    /*
    //$scope.searching = false;
    $scope.$on('searchingStatus', function (event) {
      console.log(event.targetScope.searching);
      $scope.searching = event.targetScope.searching;
    });
*/

    $scope.$on('setDestinationSuccess', function(event) {
      var ret = UserRequests.findOne({
        'state': 'new',
        'userId': Meteor.userId()
      });
      var start_xy = new AMap.LngLat(ret.location.lng, ret.location.lat);
      var end_xy = new AMap.LngLat(ret.desLocation.lng, ret.desLocation.lat);
      driving_route(start_xy, end_xy)
    });


    //导航结果展示
    function driving_routeCallBack(data, start_xy, end_xy) {
      var routeS = data.routes;
      if (routeS.length <= 0) {
        document.getElementById("result").innerHTML = "未查找到任何结果!<br />建议：<br />1.请确保所有字词拼写正确。<br />2.尝试不同的关键字。<br />3.尝试更宽泛的关键字。";
      } else {
        route_text = "";
        var allDistance = 0;
        for (var v = 0; v < routeS.length; v++) {
          //驾车步骤数
          steps = routeS[v].steps
          var route_count = steps.length;
          //行车距离（米）
          var distance = routeS[v].distance;
          allDistance += distance;
        }
        $meteor.call('setDistance', allDistance);
        $scope.map.clearMap();
        drivingDrawLine(start_xy, end_xy);
      }
    }
    //绘制驾车导航路线
    function drivingDrawLine(start_xy, end_xy) {
      //起点、终点图标
      var sicon = new AMap.Icon({
        image: "/stearen.png",
        size: new AMap.Size(44, 44),
        imageOffset: new AMap.Pixel(-334, -180)
      });
      var startmarker = new AMap.Marker({
        icon: sicon, //复杂图标
        visible: true,
        position: start_xy,
        map: $scope.map,
        offset: {
          x: -16,
          y: -40
        }
      });
      var eicon = new AMap.Icon({
        image: "/stearen.png",
        size: new AMap.Size(44, 44),
        imageOffset: new AMap.Pixel(-334, -134)
      });
      var endmarker = new AMap.Marker({
        icon: eicon, //复杂图标
        visible: true,
        position: end_xy,
        map: $scope.map,
        offset: {
          x: -16,
          y: -40
        }
      });
      //起点到路线的起点 路线的终点到终点 绘制无道路部分
      var extra_path1 = new Array();
      extra_path1.push(start_xy);
      extra_path1.push(steps[0].path[0]);
      var extra_line1 = new AMap.Polyline({
        map: $scope.map,
        path: extra_path1,
        strokeColor: "#9400D3",
        strokeOpacity: 0.7,
        strokeWeight: 4,
        strokeStyle: "dashed",
        strokeDasharray: [10, 5]
      });

      var extra_path2 = new Array();
      var path_xy = steps[(steps.length - 1)].path;
      extra_path2.push(end_xy);
      extra_path2.push(path_xy[(path_xy.length - 1)]);
      var extra_line2 = new AMap.Polyline({
        map: $scope.map,
        path: extra_path2,
        strokeColor: "#9400D3",
        strokeOpacity: 0.7,
        strokeWeight: 4,
        strokeStyle: "dashed",
        strokeDasharray: [10, 5]
      });

      var drawpath = new Array();
      for (var s = 0; s < steps.length; s++) {
        var plength = steps[s].path.length;
        for (var p = 0; p < plength; p++) {
          drawpath.push(steps[s].path[p]);
        }
      }
      var polyline = new AMap.Polyline({
        map: $scope.map,
        path: drawpath,
        strokeColor: "#9400D3",
        strokeOpacity: 0.7,
        strokeWeight: 4,
        strokeDasharray: [10, 5]
      });
      $scope.map.setFitView();
    }

    function driving_route(start_xy, end_xy) {
      var MDrive;
      AMap.service(["AMap.Driving"], function() {
        var DrivingOption = {
          //驾车策略，包括 LEAST_TIME，LEAST_FEE, LEAST_DISTANCE,REAL_TRAFFIC
          policy: AMap.DrivingPolicy.LEAST_TIME
        };
        MDrive = new AMap.Driving(DrivingOption); //构造驾车导航类 
        //根据起终点坐标规划驾车路线
        MDrive.search(start_xy, end_xy, function(status, result) {
          if (status === 'complete' && result.info === 'OK') {
            driving_routeCallBack(result, start_xy, end_xy);
          } else {
            alert(result);
          }
        });
      });
    };

    $scope.showRequest = function() {
      if ($scope.userrequests && $scope.userrequests.length > 0) {
        var request = $scope.userrequests[0];
        if (!request.desName)
          return '正在派发订单...';
        else
          return request.desName + '（' + request.distance + '米）';
      }
      return '正在派发订单...';
    };

    $scope.searching = false;
    $scope.destinations = [];
    $scope.destination = null;
    var autoSearch = function(des) {
      var keywords = des;
      var auto;
      //加载输入提示插件
      AMap.service(["AMap.Autocomplete"], function() {
        var autoOptions = {
          city: "meizhou" //城市，默认全国
        };
        auto = new AMap.Autocomplete(autoOptions);
        //查询成功时返回查询结果
        if (keywords.length > 0) {
          auto.search(keywords, function(status, result) {
            autocomplete_CallBack(result);
          });
        } else {
          $scope.destinations = [];
          $scope.searching = false;
        }
      });
    }

    var autocomplete_CallBack = function(data) {
      var tipArr = data.tips;
      $scope.destinations = tipArr;
      $scope.$apply(function() {
        $scope.searching = true;
      });

    };

    $scope.search = function(des) {
      autoSearch(des);
    };
    $scope.setDestination = function(des) {
      //console.log(des);
      $scope.searching = false;
      $meteor.call('setDestination', des.name, des.district, des.location.lng, des.location.lat).then(
        function(data) {
          $scope.$broadcast('setDestinationSuccess');
        },
        function(err) {}
      );

    };
    /*
          $scope.$watch('searching', function(newValue, oldValue) {
            $scope.$broadcast('searchingStatus');
          }, true);

    */
    $scope.resetDestination = function() {
      //console.log(des);
      $scope.destination = '';
      $scope.searching = false;
      $scope.destinations = [];
    };


    $scope.showOrders = function(order) {
      if (Roles.userIsInRole(Meteor.userId(), 'driver')) {
        var name = order.userInfo ? order.userInfo.realname : '匿名客户';
        if (order.state == 'accept')
          return '已经接受[' + (name) + ']的订单,点击开始';
        else {
          return '正在为[' + (name) + ']代驾,点击结束';
        }
      } else {
        var name = order.driverInfo ? order.driverInfo.realname : '匿名司机'
        if (order.state == 'accept')
          return '[' + (order.driverInfo.realname || '匿名') + ']已经接受你的订单';
        else {
          return '[' + (order.driverInfo.realname || '匿名') + ']正在为你代驾';
        }
      }
    }

    $scope.connectStatus = '';
    $meteor.autorun($scope, function() {
      $scope.connectStatus = Meteor.status().status;
    });
    $scope.gettingPos = false;
    $scope.clickGeo = function() {
      //console.log('clickGeo');
      /*
        $ionicLoading.show({
          template: '<ion-spinner icon="ios"></ion-spinner>\
          <a>正在定位...</a>'
        });
*/
      $scope.gettingPos = true;
      if (Meteor.isCordova)
        window.LocationPlugin.getLocation(onSuccess, onError);
      else
        Map.geolocation.getCurrentPosition();
    };
  }
]);